import {
  BrowserRouter,
  Routes,
  Route,
  Navigate,
  useLocation,
} from "react-router-dom";
import Page from "./page.js";
import Cookie from "js-cookie";

const Router = () => {

  // 拦截器
  const BeforeEach = (props) => {
    // 路由信息
    const loaction = useLocation();

    // 路由页面
    const { children } = props;

    // 判断是否登录
    if (!Cookie.get("token") && loaction.pathname !== "/login") {
      // 重定向
      return <Navigate to="/login" />;
    }

    // 正常访问
    return children;
  };

  const mapRouter = (routes) => {
    return routes.map((item, idx) => {
      return item.path ? (
        <Route
          key={idx}
          path={item.path}
          element={<BeforeEach>{item.element}</BeforeEach>}
        >
          {item.children && mapRouter(item.children)}
        </Route>
      ) : (
        <Route
          key={idx}
          path={item.from}
          element={<Navigate to={item.to} />}
        ></Route>
      );
    });
  };

  return (
    <BrowserRouter>
      <Routes>{mapRouter(Page)}</Routes>
    </BrowserRouter>
  );
};

export default Router;
